package com.ruoyi.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;
import java.util.function.Supplier;

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date()); // 起始版本 3.3.0(推荐使用)
        Long userId = SecurityUtils.getUserIdUnSafely();
        this.strictInsertFill(metaObject, "createBy", String.class, ObjectUtils.isEmpty(userId) ? null: userId.toString());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
        Long userId = SecurityUtils.getUserIdUnSafely();
        this.strictUpdateFill(metaObject, "updateBy", String.class, ObjectUtils.isEmpty(userId) ? null: userId.toString());
    }

    /**
     * 重写strictFillStrategy方法，判断字段值不为空串
     * @param metaObject
     * @param fieldName
     * @param fieldVal
     * @return
     */
    /*
    @Override
    public MetaObjectHandler strictFillStrategy(MetaObject metaObject, String fieldName, Supplier<?> fieldVal) {
        if (ObjectUtils.isEmpty(metaObject.getValue(fieldName))) {
            Object obj = fieldVal.get();
            if (Objects.nonNull(obj)) {
                metaObject.setValue(fieldName, obj);
            }
        }
        return this;
    }
    */
}
